package com.yayan.xh.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;
import java.util.Map;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import com.yayan.xh.bean.ProductBean;

public class ProductDao extends ConnectionBase implements IProductDao {
	private Connection conn = null;
	
	private QueryRunner qRunner = null;
	
	private PreparedStatement ps = null;
	
	private ResultSet rsKey = null;

	@Override
	public Map<String, Object> getProductByProId(Map<String, String> map) throws Exception {
		Map<String, Object> result = null;
		try {
			qRunner = new QueryRunner();
			String sql = "select * from tb_product where p_id=? and shop_id=?";
			conn = getConn();
			result = qRunner.query(conn, sql, new MapHandler(), map.get("productId"), map.get("shopId"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, rsKey);
		}
		return result;
	}

	@Override
	public boolean saveProduct(Map<String, String> map) throws Exception {
		boolean f = false;
		
		try {
			boolean sf = false;
			String sproductSql = "insert into tb_product(shop_id, m_id, p_name, p_type, p_price, p_createdatetime) values(?,?,?,?,?,now())";
			conn = getConn();
			conn.setAutoCommit(false);
			ps = conn.prepareStatement(sproductSql);
			ps.setObject(1, map.get("shopId"));
			ps.setObject(2, map.get("matchId"));
			ps.setObject(3, "游客票价");
			ps.setObject(4, 0);
			ps.setObject(5, map.get("sproduct"));
			sf = ps.executeUpdate() > 0 ? true : false;
			if(sf) {
				String eproductsql = "insert into tb_product(shop_id, m_id, p_name, p_type, p_price, p_createdatetime) values(?,?,?,?,?,now())";
				ps = conn.prepareStatement(eproductsql);
				ps.setObject(1, map.get("shopId"));
				ps.setObject(2, map.get("matchId"));
				ps.setObject(3, "参赛者票价");
				ps.setObject(4, 1);
				ps.setObject(5, map.get("eproduct"));
				f = ps.executeUpdate() > 0 ? true : false;
			}
			conn.commit();
			conn.setAutoCommit(true);
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, rsKey);
		}
		return f;
	}

	@Override
	public List<ProductBean> getProductByMatchIdBack(Map<String, String> map) throws Exception {
		List<ProductBean> result = null;
		try {
			qRunner = new QueryRunner();
			String sql = "select * from tb_product where m_id=? and shop_id=?";
			conn = getConn();
			result = qRunner.query(conn, sql, new BeanListHandler<ProductBean>(ProductBean.class), map.get("matchId"), map.get("shopId"));
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			close(conn, ps, rsKey);
		}
		return result;
	}

}
